<!DOCTYPE html>
<!--suppress ALL -->
<html>
<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>传智健康</title>
    <meta name="description" content="传智健康">
    <meta name="keywords" content="传智健康">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/elementui/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../css/style.css">
</head>
<body class="hold-transition">
<div id="app">
    <div class="content-header">
        <h1>工作台
            <small>用户管理</small>
        </h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>工作台</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div class="app-container">
        <div class="box">
            <div class="filter-container">
                <!--<el-input placeholder="性别/角色身份" v-model="pagination.queryString" style="width: 200px;"
                          class="filter-item"></el-input>
                <el-button @click="findPageByCondition()" class="dalfBut">查询</el-button>-->
                <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
            </div>
            <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
                <el-table-column type="index" label="序号" align="center"></el-table-column>
                <el-table-column prop="username" label="用户名" align="center"></el-table-column>
                <el-table-column prop="gender" label="适用性别" align="center">
                    <template slot-scope="scope">
                        <span>{{scope.row.gender == '1' ? '男' : '女'}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="telephone" label="联系方式" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination
                        class="pagiantion"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.currentPage"
                        :page-size="pagination.pageSize"
                        layout="total, prev, pager, next, jumper"
                        :total="pagination.total">
                </el-pagination>
            </div>
            <!-- 新增标签弹层 -->
            <div class="add-form">
                <el-dialog title="新增用户" :visible.sync="dialogFormVisible">
                    <template>
                        <el-tabs v-model="activeName" type="card">
                            <el-tab-pane label="基本信息" name="first">
                                <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right"
                                         label-width="100px">
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="用户名" prop="username">
                                                <el-input v-model="formData.username"/>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="密码" prop="password">
                                                <el-input v-model="formData.password"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="性别" prop="gender">
                                                <el-select v-model="formData.gender" >
                                                    <el-option label="男" value="1"></el-option>
                                                    <el-option label="女" value="0"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="出生年月">
                                                <!--TODO 1.添加日历-->
                                                <el-input v-model="formData.birthday"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="联系方式">
                                                <el-input v-model="formData.telephone"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="描述">
                                                <el-input v-model="formData.remark" type="textarea"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </el-tab-pane>
                            <el-tab-pane label="角色信息" name="second">
                                <div class="checkScrol">
                                    <table class="datatable">
                                        <thead>
                                        <tr>
                                            <th>选择</th>
                                            <th>角色名称</th>
                                            <th>角色标记</th>
                                            <th>角色说明</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <tr v-for="c in tableData">
                                            <td>
                                                <input :id="c.id" v-model="roleIds" type="checkbox" :value="c.id">
                                            </td>
                                            <td><label :for="c.id">{{c.name}}</label></td>
                                            <td><label :for="c.id">{{c.keyword}}</label></td>
                                            <td><label :for="c.id">{{c.description}}</label></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </template>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleAdd()">确定</el-button>
                    </div>
                </el-dialog>
            </div>

            <!-- 编辑标签弹层 -->
            <div class="add-form">
                <el-dialog title="编辑检查项" :visible.sync="dialogFormVisible4Edit">
                    <template>
                        <el-tabs v-model="activeName" type="card">
                            <el-tab-pane label="基本信息" name="first">
                                <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right"
                                         label-width="100px">
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="用户名" prop="username">
                                                <el-input v-model="formData.username"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="性别" prop="gender">
                                                <el-select v-model="formData.gender" >
                                                    <el-option label="男" value="1"></el-option>
                                                    <el-option label="女" value="0"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="出生年月">
                                                <!--TODO 1.添加日历-->
                                                <el-input v-model="formData.birthday"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="联系方式">
                                                <el-input v-model="formData.telephone"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="描述">
                                                <el-input v-model="formData.remark" type="textarea"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </el-tab-pane>
                            <el-tab-pane label="角色信息" name="second">
                                <div class="checkScrol">
                                    <table class="datatable">
                                        <thead>
                                        <tr>
                                            <th>选择</th>
                                            <th>角色名称</th>
                                            <th>角色标记</th>
                                            <th>角色说明</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <tr v-for="c in tableData">
                                            <td>
                                                <input :id="c.id" v-model="roleIds" type="checkbox" :value="c.id">
                                            </td>
                                            <td><label :for="c.id">{{c.name}}</label></td>
                                            <td><label :for="c.id">{{c.keyword}}</label></td>
                                            <td><label :for="c.id">{{c.description}}</label></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </template>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
                        <el-button type="primary" @click="handleEdit()">确定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
    </div>
</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
    var vue = new Vue({
        el: '#app',
        data: {
            activeName:"first",
            pagination: {//分页相关模型数据
                currentPage: 1,//当前页码
                pageSize: 10,//每页显示的记录数
                total: 0,//总记录数
                queryString: null//查询条件
            },
            dataList: [],//当前页要展示的分页列表数据
            tableData:[],
            roleIds:[],
            formData: {},//表单数据
            dialogFormVisible: false,//增加表单是否可见
            dialogFormVisible4Edit: false,//编辑表单是否可见
            rules: {//校验规则
                username: [{required: true, message: '用户名为必填', trigger: 'blur'}],
                password: [{required: true, message: '密码为必填', trigger: 'blur'}],
                gender: [{required: true, message: '性别为必填', trigger: 'blur'}]
            },
            //TODO 5.修改后端地址，以及下边的请求路径
            backendUrl: "http://localhost:82"
        },
        //钩子函数，VUE对象初始化完成后自动执行
        created() {
            //用来一刷新页面就查询所有的
            this.findPage();
        },
        methods: {
            //编辑
            handleEdit() {
                //点击确定触发编辑函数，获取表单数据校验
                this.$refs['dataEditForm'].validate((valid) => {
                    if (!valid) {
                        //失败，什么都不做
                        return false;
                    } else {
                        axios.defaults.withCredentials = true;
                        //成功，提交到数据库
                        axios.post(this.backendUrl + "/user/edit.do?roleIds="+this.roleIds, this.formData).then((res) => {
                            //查询所有
                            this.findPage();
                            if (res.data.flag) {
                                //修改成功,给出提示
                                this.$message({
                                    message: res.data.message,
                                    type: "success"
                                });
                            } else {
                                this.$message({
                                    message: res.data.message,
                                    type: "error"
                                });
                            }
                            //关闭弹窗
                            this.dialogFormVisible4Edit = false;
                        }).catch((err) => {
                            this.showErrorMessage(err);
                        })
                    }
                })
            },
            //添加
            handleAdd() {
                //获取表单数据校验 校验方法为validate
                this.$refs['dataAddForm'].validate((valid) => {
                    //这里valid就是校验的结果，为boolean值
                    if (!valid) {
                        //校验失败，什么都不做
                        return false;
                    } else {
                        axios.defaults.withCredentials = true
                        //校验成功，提交表单，发送请求
                        //发送ajax请求 axios 将数据添加到数据库
                        //这里的formData就是封装好的表单数据
                        axios.post(this.backendUrl + "/user/save.do?roleIds="+this.roleIds, this.formData).then((res) => {
                            //请求发送完成后
                            //查询所有并展示到页面
                            this.findPage();
                            //res就是页面返回的数据
                            console.log(res)
                            //判断页面返回数据可知是否添加成功  flag跟message都是在result类中封装好的
                            if (res.data.flag) {
                                this.$message({
                                    message: res.data.message,
                                    type: "success"
                                });
                            } else {
                                this.$message({
                                    message: res.data.message,
                                    type: "error"
                                });
                            }
                            //关闭弹窗
                            this.dialogFormVisible = false;
                        }).catch((err) => {
                            this.showErrorMessage(err);
                        })
                    }
                })
            },
            //条件查询用到的分页查询
            findPageByCondition() {
                //根据条件查询出来的数据只有一页，但是如果直接用分页查询方法，查询出来的当前页可能就是别的页码，这时候数据就不会显示
                this.pagination.currentPage = 1;
                this.findPage();
            },
            //分页查询
            findPage() {
                //封装分页查询需要的参数
                var param = {
                    currentPage: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize,
                    queryString: this.pagination.queryString
                }
                axios.defaults.withCredentials = true
                //发送分页查询的请求，展示到表格
                //这里用post，因为queryString查询条件有可能有中文
                //如果是post则加逗号加参数，如果是get，则使用地址栏的方式传参数
                axios.post(this.backendUrl + "/user/findPage.do", param).then((res) => {
                    console.log(res);
                    this.dataList = res.data.rows;
                    this.pagination.total = res.data.total;
                }).catch((err) => {
                    this.showErrorMessage(err);
                })

            },
            // 重置表单
            resetForm(dataForm) {
                //    清楚表单数据
                //（这里有双向绑定）,观察可以看出双向绑定都在formData中，所以我们令formData为空（不是null！）
                this.formData = {};
                this.roleIds=[];
                if (this.$refs[dataForm] != null) {
                    //this.$refs[表单ref属性值/名称]  获取表单对象
                    this.$refs[dataForm].resetFields();
                }
                this.activeName='first'

            },
            // 弹出添加窗口
            handleCreate() {
                //将这个变量改为true，即是显示弹窗
                this.dialogFormVisible = true;

                axios.defaults.withCredentials = true
                //发送请求，查询所有检查项
                axios.get(this.backendUrl + "/role/findAll.do").then((res) => {
                    this.tableData = res.data.data;
                }).catch((err) => {
                    console.log(err);
                });


                //重置表单
                this.resetForm('dataAddForm');
            },
            // 弹出编辑窗口
            handleUpdate(row) {
                this.dialogFormVisible4Edit = true;
                this.resetForm('dataEditForm');
                axios.defaults.withCredentials = true
                //回显数据
                axios.get(this.backendUrl + "/user/findById.do?id=" + row.id).then((res) => {
                    this.formData = res.data.data;
                    //查询所有角色
                    axios.defaults.withCredentials = true
                    axios.get(this.backendUrl+"/role/findAll.do").then((res)=>{
                        this.tableData = res.data.data;

                        //查询用户所关联的角色
                        axios.get(this.backendUrl+"/user/findRoleIdsById.do?id="+row.id).then((res)=>{
                            this.roleIds = res.data.data;
                        }).catch((err)=>{
                            this.showErrorMessage(err);
                        });
                    }).catch((err)=>{
                        this.showErrorMessage(err);
                    });
                }).catch((err) => {
                    this.showErrorMessage(err);
                })
            },
            //切换页码
            handleCurrentChange(currentPage) {
                //直接修改我们用到的参数的当前页码再调用分页查询即可即可
                this.pagination.currentPage = currentPage;
                this.findPage();
            },
            // 删除
            handleDelete(row) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.defaults.withCredentials = true;
                    //确认删除，发送请求(根据id删除)
                    axios.get(this.backendUrl + "/user/delById.do?id=" + row.id).then((res) => {
                        if (res.data.flag) {
                            this.$message({
                                message: res.data.message,
                                type: "success"
                            });
                        } else {
                            this.$message({
                                message: res.data.message,
                                type: "error"
                            });
                        }
                        //重新查询第一页，因为在直接调用分页查询的时候，如果我们删除的是最后一页且最后一页仅有一项
                        //就会发生最终查询完最后一页没有数据但是仍然显示最后一页的尴尬情况，因此我们直接从第一页开始查
                        //通过调用handlecurrentpage的方法
                        this.handleCurrentChange(1);
                    }).catch((err) => {
                        this.showErrorMessage(err);
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            showErrorMessage(err) {
                if (err == "Error: Request failed with status code 403") {
                    this.$message({
                        type: 'error',
                        message: '权限不足！'
                    });
                } else {
                    this.$message({
                        type: 'error',
                        message: '未知错误'
                    })
                }
            }
        }
    })
</script>
</html>